<?php

namespace App\Service;

use App\Constants\ErrorCode;
use App\Constants\RedisKey;
use App\Context\UserInfoContext;
use Hyperf\Context\ApplicationContext;
use Hyperf\HttpServer\Contract\RequestInterface;
use Hyperf\Redis\RedisFactory;
use Hyperf\Context\Context;
use RuntimeException;

class AdminLoginService {

    public function __construct(RequestInterface $request) {
        $apiAuth = $request->header('Api-Auth', '');
        if ($apiAuth) {
            $redis = ApplicationContext::getContainer()->get(RedisFactory::class)->get('default');
            $userInfo = $redis->get(RedisKey::ADMIN_LOGIN_AUTH . ':' . $apiAuth);
            if ($userInfo) {
                $userInfo = json_decode($userInfo, true);
            }
            if (!$userInfo || !isset($userInfo['id'])) {
                throw new RuntimeException('ApiAuth不匹配', ErrorCode::AUTH_ERROR);
            }
            $userInfoContext = (new UserInfoContext())->setUserInfo($userInfo);

            Context::set(UserInfoContext::class, $userInfoContext);
        } else {
            throw new RuntimeException('缺少ApiAuth', ErrorCode::AUTH_ERROR);
        }
    }

}
